package com.avic.rong.utils;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.text.TextUtils;

import com.avic.rong.MyApplication;
import com.avic.rong.bean.mine.OwnMessageBean;
import com.avic.rong.wedgit.StringUtil;
import com.orhanobut.logger.Logger;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.io.StreamCorruptedException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * 临时数据存储工具
 * created by xtj on 2017/12/18 9:41.
 */

public class SharedPreferencesUtil extends SharedPreferencesBase {

    private static SharedPreferences.Editor editor;
    private static SharedPreferences sharedPreferences;

    private static SharedPreferencesUtil sharedPreferencesUtil;

    public static String SIGN = "w4/b+EQcZZkXGQeiclU8w8ZP2L/6qd3TK9qGTA4nV1oLF2xTVRyFnZUlIB/KTsZWGtEfZbE8Y0R+L4yFH39qvrV9c7wc70pvjWS+8FzKmj2EnYU9dc1/bQzHe5DCESyJ";

    private final String IME_ID = "ime_id";

    private static final String DEFAULT_PREF_NAME = "user_info_pref";
    private final String USER_ID = "user_id";
    private final String USER_PHOTO = "user_photo";
    private final String USER_NAME = "user_name";
    private final String USER_PHONE = "user_phone";
    private final String IS_SIGN = "is_sign";
    private final String USER_NICK_NAME = "user_nick_name";


    private final String USER_SEX = "user_sex";
    private final String USER_EMAIL = "user_email";
    private final  String LOGIN_TOKEN = "login_token";
    private final  String LOGIN_STATE = "login_state";
    private final  String USER_INTRODUCTION = "user_introduction";
    private final  String USER_ADDRESS = "user_address";
    private final  String COMPANY_NAME = "company_name";
    private final  String COMPANY_ADDRESS = "company_address";

    private final String WXUSERJSON = "wx_UserJson";

    private final String USER_MONEY = "user_money";

    private final String FIRST_START = "first_start";

    public String getWxUserJson(){
        return getStringWithDefaultValueEmpty(WXUSERJSON);
    }

    public void setWxUserJson(String wxUserJson){
        addString(WXUSERJSON,wxUserJson);
    }


    public String getIMEID(){
       return getStringWithDefaultValueEmpty(IME_ID);
    }

    public void setIME_ID(String ime_id){
        addString(IME_ID,ime_id);
    }


    public void setFirstStart(boolean firstStart){
        addBoolean(FIRST_START,firstStart);
    }

    public boolean getFirstStart(){
        return getBooleanWithDefaultValueTrue(FIRST_START);
    }

    public void setUsermoney(String usermoney){
        addString(USER_MONEY,usermoney);
    }

    public String getUsermoney(){
        return getStringWithDefaultValueEmpty(USER_MONEY);
    }

    public static String getLoginToken(){
        return getInstance(MyApplication.getInstance()).getLogintoken();
    }
    public static String getUserID(){
        return getInstance(MyApplication.getInstance()).getUserId();
    }

    public static boolean isLogin(){
        return getInstance(MyApplication.getInstance()).getLoginState();
    }

    public SharedPreferencesUtil(Context context, String preName, int mode) {
        sharedPreferences = context.getSharedPreferences(preName, mode);
    }

    private static SharedPreferencesUtil getInstance(Context context, String preName, int mode) {
        if (sharedPreferencesUtil == null) {
            sharedPreferencesUtil = new SharedPreferencesUtil(context, preName, mode);
        }
        if (editor == null){
            editor = sharedPreferences.edit();
        }
        return sharedPreferencesUtil;
    }

    private static SharedPreferencesUtil getInstance(Context context, String preName) {
        return getInstance(context, preName, Context.MODE_PRIVATE);
    }

    public static SharedPreferencesUtil getInstance(Context context) {
        return getInstance(context, DEFAULT_PREF_NAME);
    }

    public static SharedPreferencesUtil getInstance() {
        return getInstance(MyApplication.getInstance(), DEFAULT_PREF_NAME);
    }

    @Override
    public SharedPreferences getSharedPreferences() {
        return sharedPreferences;
    }

    //普通用户的登录信息
    public String getUserId() {
        return getStringWithDefaultValueEmpty(USER_ID);


        //todo   现在写死测试  之间返回1
//        return "1";
    }

    public void setUserAddress(String userAddress){
        addString(USER_ADDRESS,userAddress);
    }

    public void setCompanyName(String companyName){
        addString(COMPANY_NAME,companyName);
    }
    public void setCompanyAddress(String companyAddress){
        addString(COMPANY_ADDRESS,companyAddress);
    }

    public String getUseraddress() {
        return getStringWithDefaultValue0(USER_ADDRESS);
    }

    public String getCompanyname() {
        return getStringWithDefaultValue0(COMPANY_NAME);
    }

    public String getCompanyaddress() {
        return getStringWithDefaultValue0(COMPANY_ADDRESS);
    }

    public String getLogintoken() {
        return getStringWithDefaultValueEmpty(LOGIN_TOKEN);
    }

    public String getUserintroduction() {
        return getStringWithDefaultValue0(USER_INTRODUCTION);
    }

    public void setLogintoken(String login_token){
        addString(LOGIN_TOKEN,login_token);
    }

    public void setLoginState(boolean login_state){
        addBoolean(LOGIN_STATE,login_state);
    }

    public boolean getLoginState(){
        return getBooleanWithDefaultValueFalse(LOGIN_STATE);
    }


    public void setUserintroduction(String introduction){
        addString(USER_INTRODUCTION,introduction);
    }

    public void setUserId(String id) {
        addString(USER_ID, id);
    }

    public String getUserPhone() {
        return getStringWithDefaultValueEmpty(USER_PHONE);

    }

    public void setUserPhone(String Phone) {
        addString(USER_PHONE, Phone);
    }

    public String getUserPhoto() {
        return getStringWithDefaultValueEmpty(USER_PHOTO);

    }

    public String getIsSign() {
        return getStringWithDefaultValueEmpty(IS_SIGN);
    }

    public void setIsSign(String isSign) {
        addString(IS_SIGN, isSign);
    }

    public void setUserPhoto(String photo) {
        addString(USER_PHOTO, photo);
    }

    public String getUserName() {
        return getStringWithDefaultValueEmpty(USER_NAME);

    }

    public void setUserName(String name) {
        addString(USER_NAME, name);
    }

    public String getUserNickName() {
        return getStringWithDefaultValueEmpty(USER_NICK_NAME);

    }

    public void setUserNickName(String name) {
        addString(USER_NICK_NAME, name);
    }

    public String getUserEmail() {
        return getStringWithDefaultValueEmpty(USER_EMAIL);

    }

    public void setUserEmail(String email) {
        addString(USER_EMAIL, email);
    }

    public String getUserSex() {
        return getStringWithDefaultValueEmpty(USER_SEX);

    }

    public void setUserSex(String sex) {
        addString(USER_SEX, sex);
    }

  /*  *
     * 保存用户信息开始
     **/
    public void setUserInfo(OwnMessageBean userVo) {
        if (userVo != null && userVo != null) {

            if (!StringUtil.isEmpty(userVo.getUserName())) {
                setUserName(userVo.getUserName());
            }
            if (!StringUtil.isEmpty(userVo.getLogo())) {
                setUserPhoto(userVo.getLogo());
            }
            if (!StringUtil.isEmpty(userVo.getNickName())) {
                setUserNickName(userVo.getNickName());
            }
           /* if (!StringUtil.isEmpty(userVo.getMemberInfo().getSex())) {
                setUserSex(userVo.getMemberInfo().getSex());
            }*/
            if (!StringUtil.isEmpty(userVo.getEmail())) {
                setUserEmail(userVo.getEmail());
            }
           /* if (!StringUtil.isEmpty(userVo.getMemberInfo().getMobilePhone())) {
                setUserPhone(userVo.getMemberInfo().getMobilePhone());
            }*/
            /*if (!StringUtil.isEmpty(userVo.getMemberInfo().getIsSign())) {
                setIsSign(userVo.getMemberInfo().getIsSign());
            }*/
            if (!StringUtil.isEmpty(userVo.getAddress())) {
                setUserAddress(userVo.getAddress());
            }
            if (!StringUtil.isEmpty(userVo.getCompanyAddress())) {
                setCompanyAddress(userVo.getCompanyAddress());
            }
            if (!StringUtil.isEmpty(userVo.getCompanyName())) {
                setCompanyName(userVo.getCompanyName());
            }

        }

    }



    /**
     * 保存用户信息结束
     **/
    public void clearUserInfo() {
        setUserId("");
        setUserName("登录/注册");
        setUserNickName("");
        setUserPhoto("");
        setIsSign("");
        setUserPhone("");
        setUserSex("");
        setUserEmail("");
        setLogintoken("");
        setLoginState(false);
        setUserintroduction("");
        setCompanyName("");
        setCompanyAddress("");
        setUsermoney("--");
        setWxUserJson("");
    }



    /**
     * 释放资源
     */
    public void release() {
        if (sharedPreferencesUtil != null) {
            sharedPreferencesUtil = null;
            System.gc();
        }
    }

    /**
     * 移除某个key
     *
     * @param key
     * @return 是否移除成功
     */
    public boolean remove(String key) {
        return editor.remove(key).commit();
    }

    /**
     * 清除所有数据
     *
     * @return 是否移除成功
     */
    public boolean clear() {
        return editor.clear().commit();
    }

    public static boolean put(String key, String value) {
        return editor.putString(key, value).commit();
    }

    public String getAsString(String key, String def) {
        return sharedPreferences.getString(key, def);
    }

    public boolean put(String key, boolean value) {
        return editor.putBoolean(key, value).commit();
    }

    public boolean getAsBoolean(String key, boolean def) {
        return sharedPreferences.getBoolean(key, def);
    }

    public boolean put(String key, int value) {
        return editor.putInt(key, value).commit();
    }

    public int getAsInt(String key, int def) {
        return sharedPreferences.getInt(key, def);
    }

    public boolean put(String key, long value) {
        return editor.putLong(key, value).commit();
    }

    public long getAsLong(String key, long def) {
        return sharedPreferences.getLong(key, def);
    }

    public boolean put(String key, float value) {
        return editor.putFloat(key, value).commit();
    }

    public float getAsFloat(String key, float def) {
        return sharedPreferences.getFloat(key, def);
    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    public boolean put(String key, Set<String> value) {
        return editor.putStringSet(key, value).commit();
    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    public Set<String> getAsStringSet(String key, Set<String> def) {
        return sharedPreferences.getStringSet(key, def);
    }


    public void putAsList(String key, List<String> list) {
        String saveStr = "";
        for (int i = 0; i < list.size(); i++) {
            if (i != list.size() - 1) {
                saveStr = saveStr + list.get(i) + ",";
            } else {
                saveStr = saveStr + list.get(i);
            }
        }
        editor.putString(key, saveStr);
        editor.commit();
    }

    public List<String> getAsList(String key) {
        List tempList = new ArrayList();
        String tempString = sharedPreferences.getString(key, "");
        String[] tempArr = tempString.split(",");
        if (tempArr.length > 0) {
            for (int i = 0; i < tempArr.length; i++) {
                if (!tempArr[i].equals(ConstantsUtils.EMPTY_STR))
                    tempList.add(tempArr[i]);
            }
        }
        return tempList;
    }

    /**
     * 保存 JSONObject数据 到 缓存中
     *
     * @param key   保存的key
     * @param value 保存的JSON数据
     */
    public void put(String key, JSONObject value) {
        saveObject(key, value);
    }

    /**
     * 读取JSONObject数据
     *
     * @param key
     * @return JSONObject数据
     */
    public JSONObject getAsJSONObject(String key) {
        Object object = readObject(key);
        if (object instanceof JSONObject) {
            return (JSONObject) object;
        }
        return null;
    }

    /**
     * 保存 JSONArray数据 到 缓存中
     *
     * @param key   保存的key
     * @param value 保存的JSONArray数据
     */
    public void put(String key, JSONArray value) {
        saveObject(key, value);
    }

    /**
     * 读取JSONArray数据
     *
     * @param key
     * @return JSONArray数据
     */
    public JSONArray getAsJSONArray(String key) {
        Object object = readObject(key);
        if (object instanceof JSONArray) {
            return (JSONArray) object;
        }
        return null;
    }

    /**
     * 保存 byte数据 到 缓存中
     *
     * @param key   保存的key
     * @param value 保存的数据
     */
    public void put(String key, byte[] value) {
        saveObject(key, value);
    }

    /**
     * 获取 byte 数据
     *
     * @param key
     * @return byte 数据
     */
    public byte[] getAsBinary(String key) {
        Object object = readObject(key);
        if (object instanceof byte[]) {
            return (byte[]) object;
        }
        return null;
    }

    /**
     * 保存 Serializable数据 到 缓存中
     *
     * @param key   保存的key
     * @param value 保存的value
     */
    public static void put(String key, Serializable value) {
        saveObject(key, value);
    }

    /**
     * 读取 Serializable数据
     *
     * @param key
     * @return Serializable 数据
     */
    public static Object getAsObject(String key) {
        Object object = readObject(key);
        if (object instanceof Serializable) {
            return (Serializable) object;
        }
        return null;
    }

    /**
     * 保存 bitmap 到 缓存中
     *
     * @param key   保存的key
     * @param value 保存的bitmap数据
     */
    public void put(String key, Bitmap value) {
        saveObject(key, value);
    }


    /**
     * 读取 bitmap 数据
     *
     * @param key
     * @return bitmap 数据
     */
    public Bitmap getAsBitmap(String key) {
        Object object = readObject(key);
        if (object instanceof Bitmap) {
            return (Bitmap) object;
        }
        return null;
    }

    /**
     * 保存 drawable 到 缓存中
     *
     * @param key   保存的key
     * @param value 保存的drawable数据
     */
    public void put(String key, Drawable value) {
        saveObject(key, value);
    }

    /**
     * 读取 Drawable 数据
     *
     * @param key
     * @return Drawable 数据
     */
    public Drawable getAsDrawable(String key) {
        Object object = readObject(key);
        if (object instanceof Drawable) {
            return (Drawable) object;
        }
        return null;
    }

    private static void saveObject(String key, Object obj) {
        try {
            //先将序列化结果写到byte缓存中，其实就分配一个内存空间
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ObjectOutputStream os = new ObjectOutputStream(bos);
            //将对象序列化写入byte缓存
            os.writeObject(obj);
            //将序列化的数据转为16进制保存
            String bytesToHexString = bytesToHexString(bos.toByteArray());
            //保存该16进制数组
            editor.putString(key, bytesToHexString);
            editor.commit();
        } catch (IOException e) {
            e.printStackTrace();
            Logger.e("", "保存obj失败");
        }
    }

    /**
     * desc:将数组转为16进制
     *
     * @param bArray
     * @return modified:
     */
    private static String bytesToHexString(byte[] bArray) {
        if (bArray == null) {
            return null;
        }
        if (bArray.length == 0) {
            return "";
        }
        StringBuffer sb = new StringBuffer(bArray.length);
        String sTemp;
        for (int i = 0; i < bArray.length; i++) {
            sTemp = Integer.toHexString(0xFF & bArray[i]);
            if (sTemp.length() < 2)
                sb.append(0);
            sb.append(sTemp.toUpperCase());
        }
        return sb.toString();
    }

    /**
     * desc:获取保存的Object对象
     *
     * @return modified:
     */
    private static Object readObject(String key) {
        try {
            if (sharedPreferences.contains(key)) {
                String string = sharedPreferences.getString(key, "");
                if (TextUtils.isEmpty(string)) {
                    return null;
                } else {
                    //将16进制的数据转为数组，准备反序列化
                    byte[] stringToBytes = StringToBytes(string);
                    ByteArrayInputStream bis = new ByteArrayInputStream(stringToBytes);
                    ObjectInputStream is = new ObjectInputStream(bis);
                    //返回反序列化得到的对象
                    Object readObject = is.readObject();
                    return readObject;
                }
            }
        } catch (StreamCorruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //所有异常返回null
        return null;

    }

    /**
     * desc:将16进制的数据转为数组
     * <p>创建人：聂旭阳 , 2014-5-25 上午11:08:33</p>
     *
     * @param data
     * @return modified:
     */
    private static byte[] StringToBytes(String data) {
        String hexString = data.toUpperCase().trim();
        if (hexString.length() % 2 != 0) {
            return null;
        }
        byte[] retData = new byte[hexString.length() / 2];
        for (int i = 0; i < hexString.length(); i++) {
            int int_ch;  // 两位16进制数转化后的10进制数
            char hex_char1 = hexString.charAt(i); ////两位16进制数中的第一位(高位*16)
            int int_ch3;
            if (hex_char1 >= '0' && hex_char1 <= '9')
                int_ch3 = (hex_char1 - 48) * 16;   //// 0 的Ascll - 48
            else if (hex_char1 >= 'A' && hex_char1 <= 'F')
                int_ch3 = (hex_char1 - 55) * 16; //// A 的Ascll - 65
            else
                return null;
            i++;
            char hex_char2 = hexString.charAt(i); ///两位16进制数中的第二位(低位)
            int int_ch4;
            if (hex_char2 >= '0' && hex_char2 <= '9')
                int_ch4 = (hex_char2 - 48); //// 0 的Ascll - 48
            else if (hex_char2 >= 'A' && hex_char2 <= 'F')
                int_ch4 = hex_char2 - 55; //// A 的Ascll - 65
            else
                return null;
            int_ch = int_ch3 + int_ch4;
            retData[i / 2] = (byte) int_ch;//将转化后的数放入Byte里
        }
        return retData;
    }



}
